package com.weilele.mvvm.view

import android.view.MotionEvent
import android.view.View
import android.view.ViewParent
import com.weilele.mvvm.utils.activity.hadScrollToBottom
import com.weilele.mvvm.utils.activity.hadScrollToEnd
import com.weilele.mvvm.utils.activity.hadScrollToStart
import com.weilele.mvvm.utils.activity.hadScrollToTop
import kotlin.math.abs

/**
 * 滚动冲突解决类
 */
open class ScrollConflictHelper(private val view: View, private val parent: ViewParent? = view.parent) {

    private var startX = 0
    private var startY = 0

    fun dispatchTouchEvent(ev: MotionEvent?) {
        ev ?: return
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = ev.x.toInt()
                startY = ev.y.toInt()
                requestDisallowInterceptTouchEvent(true)
            }
            MotionEvent.ACTION_MOVE -> {
                val endX = ev.x.toInt()
                val endY = ev.y.toInt()
                val disX = endX - startX
                val disY: Int = endY - startY
                if (abs(disX) > abs(disY)) {//本次判定为水平滚动
                    if ((disX > 0 && view.hadScrollToStart()) || (disX < 0 && view.hadScrollToEnd())) {
                        requestDisallowInterceptTouchEvent(false)
                    } else {
                        requestDisallowInterceptTouchEvent(true)
                    }
                } else {
                    if ((disY > 0 && view.hadScrollToTop()) || (disY < 0 && view.hadScrollToBottom())) {
                        requestDisallowInterceptTouchEvent(false)
                    } else {
                        requestDisallowInterceptTouchEvent(true)
                    }
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> requestDisallowInterceptTouchEvent(
                false
            )
        }
    }

    private fun requestDisallowInterceptTouchEvent(b: Boolean) {
        parent?.requestDisallowInterceptTouchEvent(b)
    }
}